package org.hbkj.springbootmybatis.service;

import org.hbkj.springbootmybatis.dao.BuysDao;
import org.hbkj.springbootmybatis.dao.GoodsDao;
import org.hbkj.springbootmybatis.entity.BuysDo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.UUID;
import java.util.Date;

@Service
public class BuysService {
    private static final Logger log = LoggerFactory.getLogger(BuysService.class);

    private final BuysDao buysDao;
    private final GoodsDao goodsDao;

    public BuysService(BuysDao buysDao, GoodsDao goodsDao) {
        this.buysDao = buysDao;
        this.goodsDao = goodsDao;
    }

    @Transactional
    public int purchase(BuysDo buysDo) {
        try {
            // 1. 生成唯一订单ID
            String orderId = UUID.randomUUID().toString().replaceAll("-", "");
            buysDo.setOrderId(orderId);
            log.info("生成订单ID：{}", orderId);

            // 2. 设置默认订单状态为"待发货"（修改点）
            if (buysDo.getOrderStatus() == null) {
                buysDo.setOrderStatus("待发货"); // 修改默认状态
            }
            log.info("订单状态：{}", buysDo.getOrderStatus());

            // 3. 设置时间戳
            Date now = new Date();
            buysDo.setCreateTime(now);
            buysDo.setUpdateTime(now);
            log.info("订单时间戳设置：{}", now);

            // 4. 扣减商品库存（使用兼容方案的新方法）
            Integer goodsId = buysDo.getGoodsId();
            Integer quantity = buysDo.getQuantity();
            log.info("准备扣减库存：商品ID={}，数量={}", goodsId, quantity);

            int stockResult = goodsDao.deductStockByIntegerId(goodsId, quantity);

            if (stockResult == 0) {
                log.warn("库存不足：商品ID={}，当前库存不足{}", goodsId, quantity);
                return 0;
            }
            log.info("库存扣减成功：商品ID={}，扣减数量={}", goodsId, quantity);

            // 5. 创建订单
            int orderResult = buysDao.createOrder(buysDo);
            if (orderResult > 0) {
                log.info("订单创建成功：订单ID={}", orderId);
            } else {
                log.error("订单创建失败：订单ID={}", orderId);
            }
            return orderResult;

        } catch (Exception e) {
            log.error("购买过程发生异常", e);
            throw new RuntimeException("购买失败：" + e.getMessage());
        }
    }
}